//
//  NoteViewController.m
//  NanNote
//
//  Created by 郑楠 on 15/5/19.
//  Copyright (c) 2015年 ___NANteam___. All rights reserved.
//

#import "NoteViewController.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface NoteViewController ()
// CoreData管理器
@property (nonatomic, retain)CoreDataManager *dataManager;
// 文本内容
@property (nonatomic, retain)UITextView *txtNote;
// 字体大小(通过block从bottomView传过来的字体大小)
@property (nonatomic, retain)NSNumber *noteFontSize;
// 字体大小(通过block从bottomView传过来的颜色号)
@property (nonatomic, retain)NSNumber *noteColor;
// 色板
@property(nonatomic, retain)ColorView *colorView;
// 色盘是否是打开状态 YES:是 NO:否
@property(nonatomic, assign)BOOL colorIsOpen;
// 底部自定义View
@property(nonatomic, retain)NoteBottomView *noteBottomView;
// 该文本内记录的图片们
@property(nonatomic, retain)NSMutableArray *imgArray;
// 铺图片的CollectionView
@property(nonatomic, retain)UICollectionView *imgCollectView;

@end

@implementation NoteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 确认添加按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(confirmAddNoteBtnClick:)];
    self.imgArray = [NSMutableArray array];
    // 文本内容
    self.txtNote = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64)];
    [self.txtNote setFont:[UIFont systemFontOfSize:18]];
    [self.view addSubview:self.txtNote];
    [self.view setBackgroundColor:[UIColor yellowColor]];
    self.dataManager = [CoreDataManager defaultCoreDataManager];
    // 底部View
    self.noteBottomView = [[NoteBottomView alloc] initWithFrame:CGRectMake(10, HEIGHT - 64 - 40, WIDTH - 20, 40)];
    self.noteBottomView.delegate = self;
    // 更新的情况
    if (self.lastUpdTime) {
        // 找到点击的那条Note(通过最后更新日期)
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"NoteEntity" inManagedObjectContext:self.dataManager.managedObjectContext];
        [fetchRequest setEntity:entity];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastUpdTime == %@", self.lastUpdTime];
        [fetchRequest setPredicate:predicate];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.dataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        
        if (fetchedObjects == nil) {
            NSLog(@"0条");
        } else {
            NoteEntity *note = fetchedObjects[0];
            [self.txtNote setFont:[UIFont systemFontOfSize:[note.fontOfSize floatValue]]];
            self.txtNote.text = [note noteContent];
            self.noteBottomView.fontSizeValue = [NSString stringWithFormat:@"%@", note.fontOfSize];
            // note颜色(默认是白色)
            [self changeBgColor:[note.noteBgColor integerValue]];
            self.noteColor = note.noteBgColor;
            self.noteFontSize = note.fontOfSize;
        }
    }
    [self.noteBottomView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.noteBottomView];
    self.colorIsOpen = NO;
    // 底部图片部分
    [self createImgScroll];
}
#pragma mark - 从NoteBottomView重写的方法
// 从ColorView传值回来(设置背景颜色)
- (void)tagOfColor:(NSInteger)tag {
    NSInteger color = tag - 10000;
    [self changeBgColor:color];
    self.noteColor = [NSNumber numberWithInteger:color];
}
// 设置字体大小
- (void)changeNoteFontSize:(NSString *)fontOfSize {
    [self.txtNote resignFirstResponder];
    [self.txtNote setFont:[UIFont systemFontOfSize:[fontOfSize floatValue]]];
    self.noteFontSize = [NSNumber numberWithInteger:[fontOfSize integerValue]];
}
// 打开颜色色板
- (void)changeNoteBgColor:(NSString *)color {
    [self.txtNote resignFirstResponder];
    self.colorIsOpen = !self.colorIsOpen;
    // 打开的状态
    if (self.colorIsOpen) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 40)];
        [self.view addSubview:bgView];
        bgView.tag = 10010;
        self.colorView = [[ColorView alloc] initWithFrame:CGRectMake(0, 0, 260, 180)];
        self.colorView.layer.borderWidth = 1;
        [bgView addSubview:self.colorView];
        self.colorView.delegate = self;
        [self.colorView setCenter:self.view.center];
    } else {
        [self.colorView removeFromSuperview];
        UIView *bgView = [self.view viewWithTag:10010];
        [bgView removeFromSuperview];
    }
}
// 分享
- (void)shareBtnClick {
    [self.txtNote resignFirstResponder];
    UIActivityViewController *shareActivityVC = [[UIActivityViewController alloc] initWithActivityItems:@[self.txtNote.text] applicationActivities:nil];
//    NSArray *activityTypes = [NSArray arrayWithObjects:UIActivityTypeMessage, nil];
//    shareActivityVC.excludedActivityTypes = activityTypes;
    [self presentViewController:shareActivityVC animated:YES completion:^{
        
    }];
}
// 图片选择
- (void)imageChooseBtnClick:(NSInteger)buttonIndex {
    UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
    imgPicker.delegate = self;
    // 摄像头
    if (buttonIndex == 0) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
    // 相册
    } else {

        [self presentViewController:imgPicker animated:YES completion:^{
            
        }];
    }
}

// imgPicker的协议方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *selectedImg = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    [self.imgArray addObject:selectedImg];
    [self.imgCollectView reloadData];
}

- (void)doneBtnClick {
    [self.txtNote resignFirstResponder];
}

# pragma mark - 本画面的按钮/collectionView必须实现的方法
// 点击保存按钮事件
- (void)confirmAddNoteBtnClick:(UIButton *)button {
    // 新规
    if (!self.lastUpdTime) {
        NSEntityDescription *noteEntity = [NSEntityDescription entityForName:@"NoteEntity" inManagedObjectContext:self.dataManager.managedObjectContext];
        NoteEntity *newNote = [[NoteEntity alloc] initWithEntity:noteEntity insertIntoManagedObjectContext:self.dataManager.managedObjectContext];
        // 备忘录内容
        newNote.noteContent = self.txtNote.text;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
        // 最后更新时间
        newNote.lastUpdTime = strDate;
        // 删除标识符 0为未删除  1为删除
        newNote.deleteFlg = @"0";
        newNote.fontOfSize = self.noteFontSize;
        newNote.noteBgColor = self.noteColor;
        if (!newNote.fontOfSize) {
            newNote.fontOfSize = [NSNumber numberWithInteger:18];
        }
    // 更新
    } else {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"NoteEntity" inManagedObjectContext:self.dataManager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastUpdTime == %@", self.lastUpdTime];
        [fetchRequest setPredicate:predicate];
        // Specify how the fetched objects should be sorted
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.dataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects.count == 0) {
            NSLog(@"0条");
        } else {
            NoteEntity *updateNote = fetchedObjects[0];
            // 备忘录内容
            updateNote.noteContent = self.txtNote.text;
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
            // 最后更新时间
            updateNote.lastUpdTime = strDate;
            // 删除标识符 0为未删除  1为删除
            updateNote.deleteFlg = @"0";
            // 字体大小
            updateNote.fontOfSize = self.noteFontSize;
            updateNote.noteBgColor = self.noteColor;
            if (!updateNote.fontOfSize) {
                updateNote.fontOfSize = [NSNumber numberWithInteger:18];
            }
        }
    }
    
    [self.dataManager saveContext];
    UIAlertView *alertMsg = [[UIAlertView alloc] initWithTitle:@"提示" message:@"操作成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alertMsg.delegate = self;
    [alertMsg show];
    [self.navigationController popViewControllerAnimated:YES];

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.imgArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ImgCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.imgView.image = self.imgArray[indexPath.row];
    return cell;
}

#pragma mark -其他
// 创建下面的图片部分
- (void)createImgScroll {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(120, 120);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 5;
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [flowLayout setSectionInset:UIEdgeInsetsMake(0, 5, 0, 5)];
    self.imgCollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(5, HEIGHT - 210, WIDTH - 10, 100) collectionViewLayout:flowLayout];
    UIView *collectBgView = [[UIView alloc] initWithFrame:self.imgCollectView.frame];
    [collectBgView setBackgroundColor:[UIColor blackColor]];
    [collectBgView setAlpha:0.1];
    [self.view addSubview:collectBgView];
    self.imgCollectView.dataSource = self;
    self.imgCollectView.delegate = self;
    [self.view addSubview:self.imgCollectView];
    [self.imgCollectView setBackgroundColor:[UIColor clearColor]];
    [self.imgCollectView registerClass:[ImgCollectCell class] forCellWithReuseIdentifier:@"reuse"];
}
// 改变背景颜色
- (void)changeBgColor:(NSInteger )color {
    // note颜色(默认是白色)
    if (color == myYellowColor) {
        [self.txtNote setBackgroundColor:[UIColor yellowColor]];
    } else if (color == myOrangeColor) {
        [self.txtNote setBackgroundColor:[UIColor orangeColor]];
    } else if (color == myCyanColor) {
        [self.txtNote setBackgroundColor:[UIColor cyanColor]];
    } else if (color == myGreenColor) {
        [self.txtNote setBackgroundColor:[UIColor greenColor]];
    } else if (color == myGrayColor) {
        [self.txtNote setBackgroundColor:[UIColor grayColor]];
    } else if (color == myWhiteColor){
        [self.txtNote setBackgroundColor:[UIColor whiteColor]];
    }
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSInteger height = keyboardRect.size.height;
    self.noteBottomView.frame = CGRectMake(10, HEIGHT - 40 - height, WIDTH - 20, 40);
    self.txtNote.frame = CGRectMake(0, 0, WIDTH, HEIGHT - height);
    
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    self.txtNote.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    self.noteBottomView.frame = CGRectMake(10, HEIGHT - 40, WIDTH - 20, 40);
    UIView *bgView = [self.view viewWithTag:10010];
    [bgView removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
